package qeug.shsh.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.ValueMapItem;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.property.ComboProp;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.ComboEdit;
import kd.bos.form.field.ComboItem;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @projectName: qeug-cosmic-root-project
 * @package: qeug.shsh.opplugin
 * @className: publicreimburPluginEx
 * @author: wenyx
 * @description: 付款申请表单插件
 * @date: 2024/2/29 14:35
 * @version: 1.0
 * 说明：付款申请单表单插件；选择资金计划和查看资金计划逻辑；应付金额、扣款金额逻辑校验；实付金额计算逻辑；计划类型过滤逻辑；付款类别字段下拉过滤逻辑；
 */
public class PublicreimburPluginEx extends AbstractFormPlugin implements BeforeF7SelectListener {

    private static String SAVE = "bar_save";//保存按钮
    private static String SUBMIT = "bar_submit";//提交按钮
    private static String UNSUBMIT = "bar_unsubmitp";//撤销按钮

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addItemClickListeners("tbmain");//监听按钮
        this.addItemClickListeners("advcontoolbarap3");
        BasedataEdit control = this.getView().getControl("qeug_settlementtype");//结算方式
        control.addBeforeF7SelectListener(this);
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        super.afterDoOperation(afterDoOperationEventArgs);
        String operateKey = afterDoOperationEventArgs.getOperateKey();
        if ("openselectplan".equals(operateKey) || "viewselectplan".equals(operateKey)) {
            //选择和查看资金计划
            HashMap<String, Object> paramters = new HashMap<>();
            DynamicObject company = (DynamicObject) this.getModel().getValue("costcompany");//费用承担公司
            DynamicObject qeug_costdept = (DynamicObject) this.getModel().getValue("qeug_costdept");//一级承担部门
            Object qeug_fundplanentry = this.getModel().getValue("qeug_fundplanentry");//资金计划行号
            Date bizdate = (Date) this.getModel().getValue("bizdate");//申请日期

            paramters.put("company", company);
            paramters.put("qeug_costdept", qeug_costdept);
            paramters.put("bizdate", bizdate);

            FormShowParameter ShowParameter = new FormShowParameter();
            ShowParameter.setFormId("qeug_queryzijh");
            paramters.put("opreationType", "open");
            paramters.put("entryid", "");
            ShowParameter.setCloseCallBack(new CloseCallBack(this, "openSelectPlan"));
            if ("viewselectplan".equals(operateKey)) {
                paramters.put("opreationType", "view");
                paramters.put("entryid", qeug_fundplanentry);
                ShowParameter.setCloseCallBack(new CloseCallBack(this, "viewSelectPlan"));
            }
            ShowParameter.getOpenStyle().setShowType(ShowType.Modal);
            ShowParameter.setCustomParams(paramters);
            //打开查询资金计划界面
            this.getView().showForm(ShowParameter);
        }
    }


    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        if ("openSelectPlan".equals(actionId)) {
            Object returnData = e.getReturnData();
            if (returnData != null) {
                //将查询资金计划中的字段设置到付款申请单中
                this.getModel().setValue("qeug_fundplanentry", ((DynamicObject) returnData).getString("qeug_entryid"));//资金计划行号
//                this.getModel().setValue("qeug_paytype", ((DynamicObject) returnData).getString("qeug_paytype"));//付款类别
                this.getModel().setValue("qeug_usefunds", ((DynamicObject) returnData).getDynamicObject("qeug_fundsuse"));//款项用途
                this.getModel().setValue("qeug_salesman", ((DynamicObject) returnData).getDynamicObject("qeug_person"));//业务员
                this.getModel().setValue("qeug_invesproject", ((DynamicObject) returnData).getString("qeug_tzproject"));//投资项目
                this.getModel().setValue("qeug_contractnum", ((DynamicObject) returnData).getString("qeug_contractnum"));//合同号
                DynamicObject qeug_fundsuse = ((DynamicObject) returnData).getDynamicObject("qeug_sffs");//结算方式
                this.getModel().setValue("qeug_settlementtype", qeug_fundsuse);//结算方式
                if (qeug_fundsuse != null) {
                    String qeug_plan_type = qeug_fundsuse.getString("qeug_plan_type");
                    this.getModel().setValue("qeug_plantype", qeug_plan_type);//计划类型
                }

            }
        }
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        Boolean automapinvoice = (Boolean) this.getModel().getValue("automapinvoice");//智能发票报销
        if (automapinvoice) {
            //智能发票报销为是的时候，付款类别只能选到应付和事项
            MainEntityType dataEntityType = this.getModel().getDataEntityType();
            ComboProp property = (ComboProp) dataEntityType.getProperty("qeug_paytype");//付款类别
            List<ValueMapItem> comboItems = property.getComboItems();
            this.getModel().setValue("qeug_paytype", null);
            List<ComboItem> comboItemss = new ArrayList<>();
            List<String> item1 = new ArrayList<>();
            item1.add("1");
            item1.add("3");
            comboItemFor(comboItems, item1, comboItemss);
            ComboEdit comboEdit = this.getControl("qeug_paytype");
            comboEdit.setComboItems(comboItemss);
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String fieldKey = e.getProperty().getName();
        if ("qeug_plantype".equals(fieldKey)) {
            //计划类型
            ChangeData[] changeSet = e.getChangeSet();
            ChangeData changeData = changeSet[0];
            Object newValue = changeData.getNewValue();//新值
            Object oldValue = changeData.getOldValue();//旧值
            DynamicObject qeug_settlementtype = (DynamicObject) this.getModel().getValue("qeug_settlementtype");//结算方式
            if (qeug_settlementtype != null) {
                Object qeug_plan_type = qeug_settlementtype.getString("qeug_plan_type");//结算方式中的计划类型
                if (!Objects.equals(newValue, oldValue) && oldValue != null && !Objects.equals(newValue, qeug_plan_type)) {
                    //计划类型修改值后，清空结算方式（附加条件：新的计划类型值与结算方式中的计划类型值不相等\\这个主要是选择资金计划后会出现）
                    getModel().setValue("qeug_settlementtype", null);//结算方式
                }
            }
        } else if ("qeug_amountpayable1".equals(fieldKey) || "qeug_deduction1".equals(fieldKey) || "invoiceno_entry".equals(fieldKey)) {
            //应付金额,扣款金额,发票号码
            ChangeData[] changeSet = e.getChangeSet();
            ChangeData changeData = changeSet[0];
            int rowIndex = changeData.getRowIndex(); //修改行所在行行号
            BigDecimal expenseAmounts = BigDecimal.ZERO;
            BigDecimal qeug_deduction1s = BigDecimal.ZERO;
            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            DynamicObjectCollection expenseEntryEntity = dataEntity.getDynamicObjectCollection("expenseentryentity");//费用明细分录
            for (DynamicObject expenseEntry : expenseEntryEntity) {
                BigDecimal expenseAmount = expenseEntry.getBigDecimal("qeug_amountpayable1");//应付金额
                BigDecimal qeug_deduction1 = expenseEntry.getBigDecimal("qeug_deduction1");//扣款金额
                expenseAmounts = expenseAmounts.add(expenseAmount);
                qeug_deduction1s = qeug_deduction1s.add(qeug_deduction1);
                if (qeug_deduction1.compareTo(expenseAmount) > 0) {
                    this.getModel().setValue("qeug_deduction1", "0", rowIndex);
                    this.getView().showErrorNotification("扣款金额不能大于应付金额");
                    return;
                }
            }
            this.getModel().setValue("qeug_amountpayable", expenseAmounts);//应付金额
            this.getModel().setValue("qeug_deduction", qeug_deduction1s);//扣款金额
            BigDecimal qeug_amount = expenseAmounts.subtract(qeug_deduction1s);//应付金额减去扣款金额
            this.getModel().setValue("qeug_amount", qeug_amount);//实付金额
        } else if ("qeug_costdept".equals(fieldKey) || "costcompany".equals(fieldKey)) {
            //公司或部门切换后清空资金计划行号，是否引用资金计划变为否，预算类型变为预算外
            ChangeData[] changeSet = e.getChangeSet();
            ChangeData changeData = changeSet[0];
            DynamicObject newValue = (DynamicObject) changeData.getNewValue();//新值
            DynamicObject oldValue = (DynamicObject) changeData.getOldValue();//旧值
            Object newId = newValue != null ? newValue.get("id") : null;
            Object oldId = oldValue != null ? oldValue.get("id") : null;
            if (newId != null && !Objects.equals(newId, oldId)) {
                getModel().setValue("qeug_budgetflag", "0");
            }
        } else if ("automapinvoice".equals(fieldKey)) {
            //智能发票报销
            ChangeData[] changeSet = e.getChangeSet();
            ChangeData changeData = changeSet[0];
            Boolean automapinvoice = (Boolean) changeData.getNewValue();//新值
            //智能发票报销为是的时候，付款类别只能选到应付和事项
            MainEntityType dataEntityType = this.getModel().getDataEntityType();
            ComboProp property = (ComboProp) dataEntityType.getProperty("qeug_paytype");//付款类别
            List<ValueMapItem> comboItems = property.getComboItems();
            this.getModel().setValue("qeug_paytype", null);
            List<ComboItem> comboItemss = new ArrayList<>();
            List<String> item1 = new ArrayList<>();
            item1.add("1");
            item1.add("3");
            List<String> item2 = new ArrayList<>();
            item2.add("2");
            if (automapinvoice) {
                comboItemFor(comboItems, item1, comboItemss);
            } else {
                comboItemFor(comboItems, item2, comboItemss);
            }
            ComboEdit comboEdit = this.getControl("qeug_paytype");
            comboEdit.setComboItems(comboItemss);
        }
    }

    private static void comboItemFor(List<ValueMapItem> comboItems, List<String> item1, List<ComboItem> comboItemss) {
        //下拉字段过滤逻辑
        ComboItem comboItem;
        for (ValueMapItem valueMapItem : comboItems) {
            String value = valueMapItem.getValue();
            //将item1包含的key设置为可见
            if (item1.contains(value)) {
                valueMapItem.setItemVisible(true);
                comboItem = new ComboItem();
                comboItem.setCaption(valueMapItem.getName());
                comboItem.setValue(value);
                comboItemss.add(comboItem);
            }
        }
    }

    @Override
    public void beforeItemClick(BeforeItemClickEvent evt) {
        super.beforeItemClick(evt);
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);
        String itemKey = evt.getItemKey();
        if ("deleteloancheck1".equals(itemKey)) {
            BigDecimal expenseAmounts = BigDecimal.ZERO;
            BigDecimal qeug_deduction1s = BigDecimal.ZERO;
            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            DynamicObjectCollection expenseEntryEntity = dataEntity.getDynamicObjectCollection("expenseentryentity");//费用明细分录
            for (DynamicObject expenseEntry : expenseEntryEntity) {
                BigDecimal expenseAmount = expenseEntry.getBigDecimal("qeug_amountpayable1");//应付金额
                BigDecimal qeug_deduction1 = expenseEntry.getBigDecimal("qeug_deduction1");//扣款金额
                expenseAmounts = expenseAmounts.add(expenseAmount);
                qeug_deduction1s = qeug_deduction1s.add(qeug_deduction1);
            }
            this.getModel().setValue("qeug_amountpayable", expenseAmounts);//应付金额
            this.getModel().setValue("qeug_deduction", qeug_deduction1s);//扣款金额
            BigDecimal qeug_amount = expenseAmounts.subtract(qeug_deduction1s);//应付金额减去扣款金额
            this.getModel().setValue("qeug_amount", qeug_amount);//实付金额
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent beforeF7SelectEvent) {
        ListShowParameter formShowParameter = (ListShowParameter) beforeF7SelectEvent.getFormShowParameter();
        List<QFilter> qFilter = new ArrayList<>();
        String value = (String) getModel().getValue("qeug_plantype");//计划类型
        if ("0".equals(value)) {
            qFilter.add(new QFilter("qeug_plan_type", QCP.equals, "0"));
            formShowParameter.getListFilterParameter().setQFilters(qFilter);
        } else if ("1".equals(value)) {
            qFilter.add(new QFilter("qeug_plan_type", QCP.equals, "1"));
            formShowParameter.getListFilterParameter().setQFilters(qFilter);
        } else if ("2".equals(value)) {
            qFilter.add(new QFilter("qeug_plan_type", QCP.equals, "2"));
            formShowParameter.getListFilterParameter().setQFilters(qFilter);
        }
    }
}
